package org.vt.scheduleapp;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class DisplayEvents extends ListActivity{
	private EventReader reader;
	private EventWriter writer;
	private List<CalendarEvent> event;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.display_events);
			
		registerForContextMenu(getListView());
		reader = new EventReader(this);
		
		event = new ArrayList<CalendarEvent>();
		try {
			event = reader.getAllEvents();
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		String[] eventStrings = new String[event.size()];
		int count = 0;
		for(CalendarEvent e : event)
		{
			eventStrings[count] = e.toString();
			count++;
		}
		setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, eventStrings));
	}
	
	protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        AlertDialog.Builder alert = new AlertDialog.Builder(
				DisplayEvents.this);
		alert.setTitle("Delete?");
		alert.setMessage("Do you want to delete this event?");

		// Set an EditText view to get user input
		//final EditText input = new EditText(ListLocations.this);
		//alert.setView(input);
		final int pos = position;
		final View v2 = v;
		alert.setPositiveButton("YES",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int whichButton) {
							event.remove(pos);
							writer = new EventWriter(v2.getContext());
							try {
								writer.writeEvent(event);
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							Intent myIntent = new Intent(v2.getContext(),
									DisplayEvents.class);
							startActivityForResult(myIntent, 0);
					}
		});
		alert.setNegativeButton("NO",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,
							int whichButton) {
						
					}
		});
		alert.show();
    }
}